import React, {Component} from 'react'
import {Radio} from 'antd'
import {TwsReactMarkdownPreview} from 'tws-antd'
import {getLangFromLocalStorage, convertContent} from '../../constant/lang-util'

const RadioGroup = Radio.Group

export default class SingleChoice extends Component {
  changeAnswer(quiz, e) {
    const answer = e.target.value
    this.props.modifyAnswer(quiz, answer.toString())
  }

  getValue(singleQuiz) {
    const preview = this.props.preview
    if (preview) {
      return parseInt(singleQuiz.answer, 10)
    }
    if (singleQuiz) {
      return parseInt(singleQuiz.userAnswer, 10)
    }
    return -1
  }

  getCorrect(singleQuiz) {
    if (singleQuiz.isCorrect) {
      return '**✅**'
    } else if (singleQuiz.isCorrect === '') {
      return ''
    } else {
      return '**❌**  '
    }
  }

  render() {
    const singleQuiz = this.props.quiz
    const {isTutor, index} = this.props
    const isCorrect = this.getCorrect(singleQuiz)
    const status = singleQuiz.answer || isTutor
    const lang = getLangFromLocalStorage()
    const description = singleQuiz[`description_${lang}`] || singleQuiz.description

    return <div className='mark-down-wrap'>
      <TwsReactMarkdownPreview source={`${index + 1}. ${description}`} />
      <div className='margin-t-1'>
        <RadioGroup
          onChange={this.changeAnswer.bind(this, singleQuiz)}
          defaultValue={this.getValue(singleQuiz)}
          disabled={!!status}>
          {singleQuiz.choices.map((option, index) =>
            <Radio className='margin-l-4 radio-style'
                   key={index}
                   value={index}>
              {option[`choice_${lang}`] || option.choice}
            </Radio>)}
        </RadioGroup>
        {status ? <TwsReactMarkdownPreview source={isCorrect}/> : ''}
      </div>
    </div>
  }
}
